import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import numeral from 'numeral';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Tabs,
  Table,
  Tooltip,
  Spin,
  Radio,
} from 'antd';
import GeneralTableComponent from 'components/GeneralTableComponent';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {
  ChartCard,
  yuan,
  MiniArea,
  MiniBar,
  MiniProgress,
  Field,
  Bar,
  Pie,
  TimelineChart,
} from 'components/Charts';

import styles from './conversionDetail.less';

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const { Option } = Select;
const confirm = Modal.confirm;
const RadioGroup = Radio.Group;

@connect(({ conversionDetail, loading }) => ({
  conversionDetail,
  loading: loading.models.conversionDetail,
}))
@Form.create()
export default class ConversionDetail extends PureComponent {
  state = {
    listParam: {
      pageNo: 1,
      pageSize: 10,
      source: '',
      name: '',
      mobile: '',
      startTime: '',
      endTime: '',
      coversionState: '',
      label: '',
      focus: '',
    },
    labelDialogVisible: false,
    labelRow: {
      label: '',
      userId: '',
    },
  };

  componentDidMount() {
    this.getDetailTableData();
    this.getRecentData();
    this.getLabels();
  }

  getLabels = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'conversionDetail/fetchGetUserLabels'
    });
  }

  getRecentData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'conversionDetail/fetchGetConversionForExternal'
    });
  }

  getDetailTableData = () => {
    const { dispatch } = this.props;
    let { listParam } = this.state;
    let postParam = {}
    for (let [key, val] of Object.entries(listParam)) {
      if (val) {
        postParam[key] = val;
      }
    }
    dispatch({
      type: 'conversionDetail/fetchGetConversionListForExternal',
      payload:{
        ...postParam
      }
    });
  }

  handleSearch = (e) => {
    const { dispatch, form } = this.props;
    const { listParam } = this.state;
    e.preventDefault();
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      //处理名字&&电话
      let _re_1 = /^[0-9]*$/,   //判断字符串是否为数字
          _re_2 = /^0\d{2,3}-?\d{0,9}$/;  //区号+号码，区号以0开头，3位或4位, 连接'-'可选
      if (_re_1.test(fieldsValue.nameOrMobile) || _re_2.test(fieldsValue.nameOrMobile)) {
        listParam.mobile = fieldsValue.nameOrMobile;
      } else {
        listParam.name = fieldsValue.nameOrMobile ? fieldsValue.nameOrMobile : '';
      }
      //处理日期
      if (fieldsValue.dateRanges && fieldsValue.dateRanges[0]) {
        [listParam.startTime, listParam.endTime] = [fieldsValue.dateRanges[0].format('YYYY-MM-DD HH:mm:ss'), fieldsValue.dateRanges[1].format('YYYY-MM-DD HH:mm:ss')];
      }
      //处理状态
      switch(fieldsValue.coversionState) {
        case 'all':
          listParam.conversionState = '';
          break;
        case 'in':
          listParam.conversionState = "转化中";
          break;
        case 'success':
          listParam.conversionState = "转化成功";
          break;
        default:
          break;
      }
      //处理是否重点关注
      switch(fieldsValue.focusState) {
        case 'all':
          listParam.focus = '';
          break;
        case 'focus':
          listParam.focus = true;
          break;
        default:
          break;
      }
      //处理标签
      switch(fieldsValue.labelState) {
        case '无':
          listParam.label = '';
          break;
        default:
          listParam.label = fieldsValue.labelState
          break;
      }
      listParam.pageNo = 1;

      this.getDetailTableData();
    });
  }

  handleFormReset = () => {
    const { form } = this.props;
    const { listParam } = this.state;
    form.resetFields();
    [listParam.mobile, listParam.name, listParam.startTime, listParam.endTime, listParam.conversionState, listParam.label, listParam.source, listParam.focus] = ['', '', '', '', '', '', ''];
    listParam.pageNo = 1;
    this.getDetailTableData();
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { listParam } = this.state;
    listParam.pageNo =  pagination.current;
    this.getDetailTableData();
  };

  handleSelectChange = (val) => {
    let { listParam } = this.state;
    listParam.source = val === 'all' ? '' : val;
    listParam.pageNo = 1;
    this.getDetailTableData();
  };

  setClassName = (record, index) => {
    return ( record.label == '重点关注' ? `${styles['l-table-row-active']}` : '')
  };

  handleChangeFocus = (text, record, operation) => {
    switch(operation) {
      case 'cancel':
        this.cancelUserFocus(record.userId);
        break;
      case 'set':
        this.setUserFocus(record.userId);
        break;
      default:
        break;
    }
  };

  cancelUserFocus = (userId) => {
    const { dispatch } = this.props;
    let postParam = {
      userId: userId,
    };
    dispatch({
      type: 'conversionDetail/fetchPostCancelFocus',
      payload: {
        ...postParam,
      },
    }).then(() => {
      this.getDetailTableData();
    });
  };

  setUserFocus = (userId) => {
    const { dispatch } = this.props;
    let postParam = {
      userId: userId,
    };
    dispatch({
      type: 'conversionDetail/fetchPostSetFocus',
      payload: {
        ...postParam,
      },
    }).then(() => {
      this.getDetailTableData();
    });
  };

  handleChangeLabel = (val, row) => {
    let { labelRow } = this.state;
    labelRow.label = row.label;
    labelRow.userId = row.userId;
    this.setState({
      labelDialogVisible: true,
    });
  };

  handleLabelOk = (e) => {
    const { dispatch } = this.props;
    const { labelRow } = this.state;
    let postParam = {
      userId: labelRow.userId,
    }
    if (labelRow.label !== '无') {
      postParam.label = labelRow.label;
    }
    dispatch({
      type: 'conversionDetail/fetchPostAddLabel',
      payload:{
        ...postParam
      }
    }).then(() => {
      this.getDetailTableData();
    });
    //clear
    let _labelRow = {
      userId: '',
      label: '',
    };
    this.setState({
      labelDialogVisible: false,
      labelRow: _labelRow,
    });
  };

  handleLabelCancel = (e) => {
    let _labelRow = {
      userId: '',
      label: '',
    };
    this.setState({
      labelDialogVisible: false,
      labelRow: _labelRow,
    });
  };

  onRadioChange = (e) => {
    let { labelRow } = this.state;
    labelRow.label = e.target.value;
  };

  renderSimpleForm() {
    const { form, conversionDetail: { getUserLabelsData } } = this.props;
    const { getFieldDecorator } = form;
    const optionItems = getUserLabelsData ? getUserLabelsData.map((item) =>
      <Option value={item} key={item}>{item}</Option>
    ) : '';

    return (
      <Card bordered={false} style={{marginBottom: 10}}>
        <Form onSubmit={this.handleSearch} layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col lg={6} md={12} sm={12}>
              <FormItem label={<span style={{width: 84, display: 'inline-block'}}>搜索</span>}>
                {getFieldDecorator('nameOrMobile')(<Input placeholder="请输入用户名或手机号"/>)}
              </FormItem>
            </Col>
            <Col lg={6} md={12} sm={24}>
              <FormItem label={<span style={{width: 84, display: 'inline-block'}}>转化描述</span>}>
                {getFieldDecorator('coversionState')(
                  <Select placeholder="全部" style={{width: 120}}>
                    <Option value="all">全部</Option>
                    <Option value="in">转化中</Option>
                    <Option value="success">转化成功</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col lg={12} md={16} sm={24}>
              <FormItem label={<span style={{width: 84, display: 'inline-block'}}>起止时间</span>}>
                {getFieldDecorator('dateRanges')(
                  <RangePicker 
                    showTime={{ format: 'HH:mm' }}
                    format="YYYY-MM-DD HH:mm"
                    placeholder={['起始时间', '结束时间']}
                  />)}
              </FormItem>
            </Col>
            <Col lg={6} md={12} sm={24}>
              <FormItem label={<span style={{width: 84, display: 'inline-block'}}>是否重点关注</span>}>
                {getFieldDecorator('focusState')(
                  <Select placeholder="全部" style={{width: 120}}>
                    <Option value="all">全部</Option>
                    <Option value="focus">重点关注</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col lg={13} md={12} sm={24}>
              <FormItem label={<span style={{width: 84, display: 'inline-block'}}>账户标签</span>}>
                {getFieldDecorator('labelState')(
                  <Select placeholder="全部" style={{width: 120}}>
                    {optionItems}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col lg={5} md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" >
                搜索
              </Button>
              <Button  htmlType="submit" style={{marginLeft:12}} onClick={this.handleFormReset}>
                清除
              </Button>
            </span>
            </Col>
          </Row>
        </Form>
      </Card>
    );
  }

  render() {
    const { conversionDetail: { conversionDetailData, conversionData, getUserLabelsData }, loading} = this.props;
    const { labelRow } = this.state;

    const radioItems = getUserLabelsData ? getUserLabelsData.map((item) =>
      <Radio value={item} key={item}>{item}</Radio>
    ) : '';

    //表头初始化
    const tableColumns = [
      {
        title: '序号',
        dataIndex: 'userId',
        key: 'userId',
        render: val => `${val}`
      },
      {
        title: '产品来源',
        dataIndex: 'source',
        key: 'source',
        render: val => `${val}`,
      },
      {
        title: '入单时间',
        dataIndex: 'registeTime',
        key: 'registeTime',
        render: val => `${val}`
      },
      {
        title: '用户名',
        dataIndex: 'name',
        key: 'name',
        render: val => `${val}`
      },
      {
        title: '年龄',
        dataIndex: 'age',
        key: 'age',
        render: val => `${val}`
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
        key: 'mobile',
        render: val => `${val}`
      },
      {
        title: '转化描述',
        dataIndex: 'conversionDesc',
        key: 'conversionDesc',
        render: val => `${val}`
      },
      {
        title: '进行阶段',
        dataIndex: 'period',
        key: 'period',
        render: val => `${val}`
      },
      {
        title: '关注',
        dataIndex: 'focus',
        key: 'focus',
        render: (text, record) => (
          <div>
            { 
              record.focus ? 
              <Icon type="star" theme="filled" style={{'fontSize': 20, color: '#1890ff', cursor: 'pointer'}}
              onClick={() =>{this.handleChangeFocus(text,record,'cancel')}}
              />
              : 
               <Icon type="star" theme="twoTone" style={{'fontSize': 20, cursor: 'pointer'}} twoToneColor="#e6f7ff" onClick={() =>{this.handleChangeFocus(text,record,'set')}}/>
            }
          </div>
        )
      },
      {
        title: '标签',
        dataIndex: 'label',
        key: 'label',
        render: (text, record) => (
          <div>
            <span> {record.label === '/' ? '' : record.label} </span>
            { 
              record.label !== '/' ?
              <Icon type="edit" theme="outlined" style={{cursor: 'pointer', color: '#1890ff'}} onClick={() =>{this.handleChangeLabel(text,record)}} />
              : 
              <Icon type="plus-circle" theme="twoTone" style={{cursor: 'pointer', 'fontSize': 20}} onClick={() =>{this.handleChangeLabel(text,record)}} />
            }
          </div>
        )
      },
    ];

    const topColProps = {
      xs: 24,
      sm: 24,
      md: 8,
      lg: 8,
      xl: 8,
    };

    return (
      <PageHeaderLayout title="转化详情">
        {
          conversionData ?
          <Row gutter={{ md: 8, lg: 24, xl: 48 }} style={{marginBottom: 20, marginLeft: 20, marginRight: 20}}>
            <Col {...topColProps}>
              <ChartCard
                bordered={false}
                title='昨日转化率'
                footer={
                  <Col style={{ 'textAlign': 'center' }}>
                    <Field label="" value={conversionData.yesterdayConversion ? conversionData.yesterdayConversion.withdrawConversion : '/'} />
                  </Col>
                }
              >
              </ChartCard>
            </Col>
            <Col {...topColProps}>
              <ChartCard
                bordered={false}
                title='今日入单数'
                footer={
                  <Col style={{ 'textAlign': 'center' }}>
                    <Field label="" value={conversionData.todayConversion ? conversionData.todayConversion.passCount : '/'} />
                  </Col>
                }
              >
              </ChartCard>
            </Col>
            <Col {...topColProps}>
              <ChartCard
                bordered={false}
                title='今日转化单数'
                footer={
                  <Col style={{ 'textAlign': 'center' }}>
                    <Field label="" value={conversionData.todayConversion ? conversionData.todayConversion.withdrawSuccessCount : '/'} />
                  </Col>
                }
              >
              </ChartCard>
            </Col>
          </Row>
          : <Spin />
        }
        
        <Card bordered={false}>
          <div>{this.renderSimpleForm()}</div>
          <div style={{marginBottom: 10}}>
            <span>产品来源: </span>
            <Select defaultValue="all" style={{width: 120}} onChange={this.handleSelectChange}>
              <Option value="all">全部</Option>
              <Option value="up">sdfz</Option>
              {/* <Option value="xflower">信花花</Option>
              <Option value="xbeauty">想美</Option> */}
            </Select>
          </div>
          <GeneralTableComponent
            loading={loading}
            data={conversionDetailData}
            columns={tableColumns}
            onChange={this.handleStandardTableChange}
            // handleRowClass={this.setClassName}
          />
        </Card>

        <Modal
          title="Basic Modal"
          visible={this.state.labelDialogVisible}
          onOk={this.handleLabelOk}
          onCancel={this.handleLabelCancel}
        >
          <RadioGroup onChange={this.onRadioChange} defaultValue={labelRow.label}>
            {radioItems}
          </RadioGroup>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
